package com.dxt.netty;

import com.dxt.common.AppConstant;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

@Component
public class RuiKongYdServer {
    private static final Logger logger = LoggerFactory.getLogger(Thread.currentThread().getStackTrace()[1].getClassName());

    public void start(int port) {
        // netty服务端ServerBootstrap启动的时候,默认有两个eventloop分别是bossGroup和 workGroup
        EventLoopGroup boosGroup = new NioEventLoopGroup(1024);   // bossGroup
        EventLoopGroup workerGroup = new NioEventLoopGroup();  // workGroup
        try {
            ServerBootstrap sbs = new ServerBootstrap().group(boosGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast("decoder", new StringDecoder());
                            ch.pipeline().addLast("encoder", new StringEncoder());
                            ch.pipeline().addLast(new IdleStateHandler(
                                    AppConstant.SYS_CONSTANT.SERVER_READ_IDEL_TIME_OUT,
                                    AppConstant.SYS_CONSTANT.SERVER_WRITE_IDEL_TIME_OUT,
                                    AppConstant.SYS_CONSTANT.SERVER_ALL_IDEL_TIME_OUT,
                                    TimeUnit.SECONDS));
                            ch.pipeline().addLast(new RuiKongYdServerHandler());
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(1032, 1032, 2048))
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture future = sbs.bind(port).sync();
            if (future.isSuccess()) {
                logger.info(String.format("Netty server: [%d]", port));
            }
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
